<template>
	<div>
		<div class="datasource-static">
			<el-table
				border
				lazy
				row-key="id"
				:data="state.tableData"
				:load="loadChildrenData"
				:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
				style="width: 100%; margin-bottom: 10px"
				size="small"
				class="data-field-test-table"
				:row-style="state.tableRowStyle"
				:cell-style="state.tableRowCellStyle">
				<el-table-column prop="field" label="字段" width="110px"></el-table-column>
				<el-table-column prop="mapping" label="映射">
					<template #default="scope">
						<el-select
							v-model="scope.row.mapping"
							placeholder="请选择"
							size="small"
							class="data-field-selector">
							<el-option
								v-for="item in state.selectVerifyValueOptions"
								:key="item.value"
								:label="item.label"
								:value="item.value"
								:default-first-option="state.selectVerifyValueOptions.index"></el-option>
						</el-select>
					</template>
				</el-table-column>
				<el-table-column prop="explain" label="说明" width="80px"></el-table-column>
				<el-table-column prop="status" label="状态" width="32px">
					<template #default="scope">
						<el-icon
							v-if="scope.row.status == 'passed'"
							class="el-icon-check"
							style="color: green; font-size: 16px">
							<Check />
						</el-icon>
						<el-icon
							v-if="scope.row.status == 'nopass'"
							class="el-icon-close"
							style="color: red; font-size: 16px">
							<Close />
						</el-icon>
					</template>
				</el-table-column>
			</el-table>
			<CodeEditorVue
				class="datasource-static-code"
				v-model:code="state.editorText"
				ref="editor"></CodeEditorVue>
			<el-row type="flex">
				<el-col :span="12" style="display: flex; align-items: center">
					<el-checkbox
						v-model="state.dataSourceFilterChecked"
						@change="changeDataSourceFilterChecked">
						数据过滤器:
					</el-checkbox>
				</el-col>
				<el-col :span="12" style="flex: 1; text-align: right">
					<el-button type="primary" @click="openDataFilterDrawer" size="small">
						编辑过滤器
					</el-button>
				</el-col>
			</el-row>
		</div>
		<DashboardDataFilter
			ref="dashboardDataFilter"
			v-model:visible="state.dashboardDataFilterVisible"
			:dataToResponseData="state.editorText"
			:instance="props.instance"
			@getDataFilter="getDataFilter" />
	</div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, inject, toRefs, watch, ref } from 'vue';
import CodeEditorVue from './CodeEditor.vue';
import _ from 'lodash';
import { RUNTIME_CFG_ENUM } from '@CIF/Runtime/Global/variable';
import StorageHelper from '@CIF/Runtime/Global/storage';
import DashboardDataFilter from './DataFilterDashboard.vue';
// import { usePrimaryStore } from '@/store';
// import { ElMessage } from 'element-plus';

// const store = usePrimaryStore();
const cpntFrame: any = inject('cpntFrame');
const props = defineProps({
	instance: {
		type: Object,
		default() {
			return {};
		}
	}, // cpntTreeNode
	setConfiguredDataToInstance: {
		type: Function,
		default() {
			return () => {};
		}
	}
});
const state: any = reactive({
	tableRowStyle: {
		padding: 0
	},
	tableRowCellStyle: {
		padding: 0
	},
	tableData: [], //上方数据校验表格数据集
	selectVerifyValueOptions: [], //table中映射字段下拉框数据集
	fields: [
		{
			id: 1,
			name: 'disabled', // 字段
			value: 'disabled', // 映射
			desc: '是否启用' // 说明
		},
		{
			id: 2,
			name: 'label',
			value: 'label',
			desc: '标签'
		},
		{
			id: 3,
			name: 'opacity',
			value: 'opacity',
			desc: '透明度'
		},
		{
			id: 4,
			name: 'type',
			value: 'type',
			desc: '类型'
		},
		{
			id: 5,
			name: 'children',
			value: 'children',
			desc: '子节点',
			children: [
				{
					id: 6,
					name: 'disabled',
					value: 'disabled',
					desc: '是否启用'
				},
				{
					id: 7,
					name: 'label',
					value: 'label',
					desc: '标签'
				},
				{
					id: 8,
					name: 'opacity',
					value: 'opacity',
					desc: '透明度'
				},
				{
					id: 9,
					name: 'type',
					value: 'type',
					desc: '类型'
				}
			]
		}
	], // TODO: 校验字段（目前写死在这里，后续优化）
	dataSourceFilterChecked: false, //数据过滤器选中状态
	dashboardDataFilterVisible: false, //数据过滤器弹窗显隐控制
	editorText: JSON.stringify(props.instance.data, null, 4), // CodeEditor 输入框绑定数据
	isPass: '', //table中检测当前行数据是否校验通过
	tableChildrenData: [], //table中children子数据集
	tmpDataFilter: _.clone({
		filterCbVar: _.get(props.instance, 'filterCbVar'),
		filterFn: _.get(props.instance, 'dataFormatter').filterFn || 'return data'
	})
});
watch(
	() => state.editorText,
	(nv) => {
		state.editorText = nv;
	}
);
const editor = ref();
//存值至instance
function saveDataToInstance() {
	editor.value.emitCode();
	if (_.get(window, 'cif.config.logger.enable', false) === true) {
		console.log(
			'CIF.CC.DC.C.DataSourceTypeofStatic:saveDataToInstance ',
			JSON.parse(state.editorText)
		);
	}
	// this.instance.data = JSON.parse(this.editorText)
	// 过滤器也放在这里保存
	// filterCbVar: this.tmpInteractionFilterArgs,
	// filterFn: this.filterFunctionBody
	props.setConfiguredDataToInstance(props.instance.uuid, {
		filterCbVar: state.tmpDataFilter.filterCbVar,
		dataFormatter: {
			filterFn: state.tmpDataFilter.filterFn,
			active: state.dataSourceFilterChecked
		},
		data: JSON.parse(state.editorText)
	});
	if (StorageHelper.get(RUNTIME_CFG_ENUM.CIF_MODE) === RUNTIME_CFG_ENUM.DEV_MODE) {
		try {
			// debugger;
			// console.log(1111, cpntFrame.container.value.getCpntWrapperById(props.instance.uuid));
			cpntFrame &&
				cpntFrame.container.value.getCpntWrapperById(props.instance.uuid).exposed.updateCpntData();
		} catch (e) {
			if (_.get(window, 'cif.config.logger.enable', false) === true) {
				console.log('CIF.CC.DC.C.DataSourceTypeofStatic:setConfiguredDataToInstance fail!', e);
			}
		}
	}
}
function changeDataSourceFilterChecked(checked: any) {
	state.dataSourceFilterChecked = checked;
	// TODO: 是否启用数据过滤器的选择需要保存回组件实例
}
function openDataFilterDrawer() {
	state.dashboardDataFilterVisible = true;
}

function getDataFilter(dataFilter: any = {}) {
	state.tmpDataFilter = dataFilter;
}

//格式化json静态数据方法，不使用eval()函数！
function getJson(json: any) {
	return Function('"use strict";return (' + json + ')')();
}
//判断校验是否通过
function filterPassOrNot(val: any, item: any) {
	try {
		for (let i = 0; i < getJson(val).length; i++) {
			let d = getJson(val)[i];
			if (Object.keys(d).some((key) => item == key)) {
				if (state.isPass == 'nopass') {
					state.isPass = 'nopass';
				} else {
					state.isPass = 'passed';
				}
			} else {
				state.isPass = 'nopass';
			}
		}
		return state.isPass;
	} catch (e) {
		state.isPass = 'nopass';
		return state.isPass;
	}
}
//校验状态重置方法
function refreshIsPass() {
	state.isPass = '';
}

// 初始化table数据
function initFieldsTableData(val: any) {
	let tempFileds = state.fields;
	// delete tempFileds.children;
	// if (_.get(window, "cif.config.logger.enable", false) === true) {
	//   console.log("CIF.CC.DC.C.DataSourceTypeofStatic:initFieldsTableData tempFileds", tempFileds)
	// }
	let verifyValue = [];
	let verifyTableData = [];
	let verifyTableChildrenData = [];
	for (let k in tempFileds) {
		let tempF: any = tempFileds[k];
		let i = 0;
		if (i < Object.keys(tempFileds).length) {
			i++;
			//拼凑table中映射下拉框数据
			verifyValue.push({ label: tempF.name, value: tempF.name });
			//拼凑table数据源
			if (tempF.name == 'children') {
				verifyTableData.push({
					id: tempF.id,
					field: tempF.name,
					mapping: tempF.name,
					explain: tempF.desc,
					status: filterPassOrNot(val, tempF.name),
					hasChildren: true
				});
			} else {
				verifyTableData.push({
					id: tempF.id,
					field: tempF.name,
					mapping: tempF.name,
					explain: tempF.desc,
					status: filterPassOrNot(val, tempF.name)
				});
			}
			refreshIsPass();
		}
		//拼凑table中子节点数据源
		if (
			Object.keys(tempF).some((k) => k === 'children') ||
			(Array.isArray(state.tableChildrenData) && state.tableChildrenData.length === 0)
		) {
			for (let k1 in tempF.children) {
				let tempF1 = tempF.children[k1];
				let j = 0;
				if (j < Object.keys(tempF.children[k1]).length) {
					j++;
					verifyTableChildrenData.push({
						id: tempF1.id,
						field: tempF1.name,
						mapping: tempF1.name,
						explain: tempF1.desc,
						status: ''
					});
				}
			}
		}
	}
	state.selectVerifyValueOptions = verifyValue;
	state.tableData = verifyTableData;
	state.tableChildrenData = verifyTableChildrenData;
	// if (_.get(window, "cif.config.logger.enable", false) === true) {
	//   console.log("CIF.CC.DC.C.DataSourceTypeofStatic:initFieldsTableData tableData", this.tableData)
	//   console.log("CIF.CC.DC.C.DataSourceTypeofStatic:initFieldsTableData tableChildrenData", this.tableChildrenData)
	// }
}

function loadChildrenData(tree: any, treeNode: any, resolve: any) {
	setTimeout(() => {
		resolve(state.tableChildrenData);
	}, 1000);
}

onMounted(() => {
	initFieldsTableData(state.editorText);
});
defineExpose({ ...toRefs(state), saveDataToInstance });
</script>

<style lang="scss" scoped>
.datasource-static {
	&-left-label {
		float: left;
		margin-top: 5px;
	}
	&-code {
		height: 450px;
		margin-top: 10px;
		margin-bottom: 10px;
		border: solid 1px rgba(6, 206, 173, 0.78);
		border-radius: 2px;
	}
	&-checkbox {
		margin-top: 10px;
	}
}

.datasource-static-code {
	::v-deep .CodeMirror {
		height: 100%;
		width: 100%;
	}
}

.down-btn-area {
	position: relative;
	width: 400px;
	bottom: 0;
	right: 0;
	background-color: transparent;
}

.data-field-test-table {
	::v-deep th {
		padding: 0;
		vertical-align: middle;
		line-height: 32px;
		height: 32px;
	}
	::v-deep td {
		padding: 0;
		vertical-align: middle;
		line-height: 32px;
		height: 32px;
	}

	::v-deep .cell {
		padding: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 32px;
	}

	::v-deep .el-table__empty-block {
		min-height: 32px;
		height: 32px !important;
	}

	.data-field-selector {
		padding: 0 4px;
	}
}
</style>
